﻿using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour {

	public Spouse highlightedSpouse;

	public float moveSpeed = 0.01f;

	public static Player _instance;

	// Use this for initialization
	void Awake () 
	{
		m_property = GetComponent<HumanProperty> ();
		m_reference = GameObject.Find ("reference").GetComponent<Reference> ();
		m_likenessLabel = GameObject.Find ("likeness").GetComponent<UILabel> ();
		m_likenessLabel.enabled = false;
		_instance = this;
	}

	void Start()
	{
		m_property.UpdateShow();
	}
	
	// Update is called once per frame
	void Update () 
	{
		if (Input.GetKey(KeyCode.LeftArrow))
		{
			gameObject.transform.position += new Vector3(-moveSpeed, 0, 0);
		}
		else if (Input.GetKey(KeyCode.RightArrow))
		{
			gameObject.transform.position += new Vector3(moveSpeed, 0, 0);
		}

		if (Input.GetKeyDown (KeyCode.Space)) 
		{
			PlayerSpouse();	
		}

		if (Input.GetKeyDown (KeyCode.R))
		{
			Application.LoadLevel("Main");
		}
	}

	private void PlayerSpouse()
	{
		if (highlightedSpouse != null)
		{
			Debug.Log("I choose this one: " + highlightedSpouse.name);	
			++m_timesBred;
			
			this.transform.position -= new Vector3(0.0f, 0.45f, 0.0f);
			
			m_property.Combine(highlightedSpouse.m_property);
			m_property.UpdateShow();
			
			if (m_timesBred >= 3)
			{
				//Debug.Log("Likeness: " + m_reference.Compare());
				m_likenessLabel.text = "相似度 :" + ((int)(m_reference.Compare() * 100.0f)).ToString() + "%";
				m_likenessLabel.enabled = true;
			}
		}
	}

	public void Spouse(HumanProperty property)
	{
		if(!CheckValid(property))
		{
			return;
		}

		++m_timesBred;

		if (m_timesBred == 1) {
						GameObject.Find ("Model1").SetActive (false);

				} else if(m_timesBred == 2){
			GameObject.Find ("Model2").SetActive (false);
		}
		
		this.transform.position -= new Vector3(0.0f, 0.50f, 0.0f);
		
		m_property.Combine(property);
		m_property.UpdateShow();
		
		if (m_timesBred >= 3)
		{

			//m_likenessLabel.text = "相似度 :" + ((int)(m_reference.Compare() * 100.0f)).ToString() + "%";
			m_likenessLabel.text = ((int)(m_reference.Compare() * 100.0f)).ToString();
			m_likenessLabel.enabled = true;
		}
	}

	public bool CheckValid(HumanProperty property)
	{
		string name = property.gameObject.name;
		if(m_timesBred == 0 && (name == "Human1" || name == "Human2" || name == "Human3"))
		{
			return true;
		}

		if(m_timesBred == 1 && (name == "Human4" || name == "Human5" || name == "Human6"))
		{
			return true;
		}

		if(m_timesBred == 2 && (name == "Human7" || name == "Human8" || name == "Human9"))
		{
			return true;
		}

		return false;
	}

	public void RestartLevel()
	{
		Application.LoadLevel("Main");
	}

	private HumanProperty m_property;
	private HumanProperty m_spouseProperty;
	private Reference m_reference;
	private int m_timesBred = 0;
	private UILabel m_likenessLabel;
}
